import Compressor from 'compressorjs';


export const base64Encode = (str) => {
    // 将字符串转换为 UTF-8 编码的字节数组
    const utf8Bytes = new TextEncoder().encode(str);
    // 将字节数组转换为 Base64 字符串
    return btoa(String.fromCharCode.apply(null, utf8Bytes));
};

export const base64Decode = (base64) => {
    // 将 Base64 字符串转换为字节数组
    const byteString = atob(base64);
    // 将字节数组转换为 UTF-8 字符串
    const bytes = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
        bytes[i] = byteString.charCodeAt(i);
    }
    return new TextDecoder().decode(bytes);
};

export const goPageByPath = (path, query = {}) => {
    if (!path) {
        throw new Error('缺少必须的path参数');
    }
    let queryLen = Object.keys(query).length;
    let queryStr = '';
    if (queryLen) {
        queryStr = Object.keys(query)
            .map((key) => `${key}=${query[key]}`)
            .join('&');
        queryStr = `?${queryStr}`;
    }
    uni.navigateTo({url: `${path}${queryStr}`});
};

// 临时路径转file对象 针对h5端
export const tempFilePathToFile = ({tempFilePath, fileName}) => {
    if (!tempFilePath) {
        return Promise.resolve(null);
    }
    return new Promise(async (resolve, reject) => {
        try {
            const response = await fetch(tempFilePath);
            const blob = await response.blob();
            const mimeType = response.headers.get('content-type');
            const file = new File([blob], fileName, {type: mimeType});
            resolve(file);
        } catch (error) {
					console.log(error)
            resolve(null);
        }
    });
};

// 压缩文件
export const compressFile = (file, options) => {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
            ...options,
            success(result) {
                resolve(result);
            },
            error(err) {
                reject(err);
            },
        });
    });
};


// 节流工具函数
export function throttle(fn, delay = 1000) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
}

export function debounce(fn, delay = 1000) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}